package com.lz.comm.viewmodel

import android.util.ArrayMap
import androidx.room.RoomDatabase
import com.lz.comm.net.DataRepository
import com.lz.library.base.BaseModel
import com.lz.library.base.Repository

/**
 *  author: you : 2020/05/31
 *  def data model
 */
class DataModel(repository: Repository = DataRepository) : BaseModel(repository) {

    private val services = ArrayMap<Class<*>, Any>()

    private val databases = ArrayMap<Class<out RoomDatabase>, RoomDatabase>()

    override fun onCleared() {
        services.clear()
        databases.forEach { it.value.close() }
        databases.clear()
    }

    fun <T> getService(serviceClass: Class<T>): T {
        val service = services[serviceClass]
        if (service != null) return service as T
        return repository.getService(serviceClass).also { services[serviceClass] = it }
    }

    fun <T : RoomDatabase> getRoomDatabase(databaseClass: Class<T>, dbName: String): T {
        val database = databases[databaseClass]
        if (database != null) return database as T
        return repository.getRoomDatabase(databaseClass, dbName).also { databases[databaseClass] = it}
    }
}